package com.live.controller.interfaced;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamsOnlineListRequest;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import com.honour.service.interfaced.UserInManager;
import com.honour.service.interfaced.impl.CircleInService;
import com.live.service.interfaced.impl.LiveInService;
import com.live.util.LiveUtil;
import com.system.controller.base.BaseController;
import com.system.redis.RedisDao;
import com.system.util.AppUtil;
import com.system.util.DateUtil;
import com.system.util.PageData;
import com.system.util.SnowIdUtil;
import com.system.util.Tools;
import com.system.util.ToolsUtil;

import redis.clients.jedis.Tuple;

/**
 * 直播接口
 * 
 * @Function
 * @Author 于泓磊
 * @Date 2018年1月19日
 */
@Controller
@RequestMapping(value = "/applivein")
public class LiveInController extends BaseController {

	@Resource(name = "liveInService")
	private LiveInService liveInService;
	@Resource(name = "userinService")
	private UserInManager userinService;
	@Resource(name = "circleInService")
	private CircleInService circleInService;

	private static Gson gson = new Gson();

	@Resource(name = "redisDaoImpl")
	private RedisDao redisDaoImpl;

	public LiveInService getLiveInService() {
		return liveInService;
	}

	@Resource(name = "liveInService")
	public void setLiveInService(LiveInService liveInService) {
		this.liveInService = liveInService;
	}

	/**
	 * @Function 获得所有正在推流的地址(所有正在直播的地址)
	 * @Author 于泓磊
	 * @Date 2018年1月19日
	 */
	@RequestMapping(value = "/getpushlist")
	@ResponseBody
	public Object getPushList() {
		logBefore(logger, "获得所有正在推流的地址(所有正在直播的地址)");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("PUSHLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				pd = getPushOnline(pd, "live.rongyaohk.com", "ZSHApp");
				String json = (String) pd.get("PUSHONLINE");
				PageData pdjson = gson.fromJson(json, PageData.class);
				pd.put("PUSHONLINE", pdjson);
				map.put("pd", pd);
				result = (null == pd) ? "02" : "01";
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 获得附近所有的直播推流地址
	 * @Author 于泓磊
	 * @Date 2018年1月19日
	 */
	@RequestMapping(value = "/getnearbypushlist")
	@ResponseBody
	public Object getNearByPushList() {
		logBefore(logger, "获得附近所有的直播推流地址");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("PUSHNEARLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) { // 检查参数(检验HONOURUSER_ID)
					pd = getNearByPushOnline(pd.getString("HONOURUSER_ID"), "live.rongyaohk.com", "ZSHApp");
					String json = (String) pd.get("PUSHONLINE");
					PageData pdjson = gson.fromJson(json, PageData.class);
					pd.put("PUSHONLINE", pdjson);
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 主播开播接口(获取一个推流地址)
	 * @Author 于泓磊
	 * @Date 2018年1月19日
	 */
	@RequestMapping(value = "/getpushaddress")
	@ResponseBody
	public Object getPushAddress() {
		logBefore(logger, "主播开播接口(获取一个推流地址)");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("PUSHADDRESS", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("PushLive", pd)) { // 检查参数
					PageData userPortrait = userinService.getUserPortrait(pd);
					pd.put("LIVE_COVER", userPortrait.getString("PORTRAIT"));
					pd.put("LIVE_ID", this.getSnowId());
					// 检测数据库有无该用户开播记录，如果有则不新建，只修改数据库记录
					if (liveInService.getCountByUserId(pd).getLong("UCOUNT") > 0) {
						liveInService.updLiveOnline(pd);
					} else {
						liveInService.addLiveOnline(pd);
					}
					pd = getPushAddress(pd.getString("HONOURUSER_ID"), "ZSHApp", "game");
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		System.out.println(AppUtil.returnObject(new PageData(), map));
		return AppUtil.returnObject(new PageData(), map);
	}


	/**
	 * @Function 获取直播所有的分类接口
	 * @Author 于泓磊
	 * @Date 2018年1月24日
	 */
	@RequestMapping(value = "/getlivetypelist")
	@ResponseBody
	public Object getLiveTypeList() {
		logBefore(logger, "获取直播所有的分类接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("LIVETYPE", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (pd.get("PARENT_ID") == null) {
					pd.put("PARENT_ID", 0);
				}
				List<PageData> list = liveInService.getLiveTypeList(pd);
				if (list.size() != 0) {
					map.put("pd", list);
				}
				result = (0 == list.size()) ? "02" : "01";
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 尚播中筛选接口
	 * @Author 于泓磊
	 * @Date 2018年2月2日
	 */
	@RequestMapping(value = "/getscreenlist")
	@ResponseBody
	public Object getScreenList() {
		logBefore(logger, "尚播中筛选接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("SCREENLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("screenList", pd)) { // 检查参数(检验HONOURUSER_ID)
					String beforeWithSecond = "";
					switch (Integer.parseInt(pd.getString("LIVE_START"))) {
					// 15分钟内
					case 15:
						beforeWithSecond = DateUtil.getBeforeWithSecond(900);
						break;
					// 2小时之内
					case 2:
						beforeWithSecond = DateUtil.getBeforeWithSecond(7200);
						break;
					// 1天内
					case 1:
						beforeWithSecond = DateUtil.getBeforeWithDays(1);
						break;
					// 7天内
					case 7:
						beforeWithSecond = DateUtil.getBeforeWithDays(7);
						break;
					case 0:
						break;
					}
					if (pd.getString("SEX").equals("全部")) {
						pd.put("SEX", "");
					}
					// 如果类型为开播吧，则筛选正在直播的接口
					if (("LIVE").equals(pd.getString("TYPE"))) {
						pd.put("LIVE_START", beforeWithSecond);
						pd = getScreenOnline(pd, "live.rongyaohk.com", "ZSHApp");
						String json = (String) pd.get("PUSHONLINE");
						pd.put("PUSHONLINE", gson.fromJson(json, PageData.class));
						map.put("pd", pd);
						result = (null == pd) ? "02" : "01";
					} else if (("WEIBO").equals(pd.getString("TYPE"))) {//类型为微博
						pd.put("PUBLISHTIME", beforeWithSecond);
						List<PageData> screenList = circleInService.getScreenList(pd);
						if (screenList.size() != 0) {
							map.put("pd", screenList);
						}
						result = (0 == screenList.size()) ? "02" : "01";
					} else if (("WULI").equals(pd.getString("TYPE"))) {
						pd.put("LIVE_START", beforeWithSecond);

					}

				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 接受推流回调信息
	 * @Author 于泓磊
	 * @Date 2018年1月30日
	 */
	@RequestMapping(value = "/checkpushoff")
	public void checkPushOff(HttpServletResponse response) {
		logBefore(logger, "接受推流回调信息");
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd.put("StreamName", pd.getString("id"));
			PageData pp = liveInService.getLiveCoverTitle(pd);
			pp.put("HONOURUSER_ID", pp.get("HONOURUSER_ID"));
			// 将数据库中主播状态进行更改
			if (pd.getString("action").equals("publish")) {
				pp.put("LIVE_ONLINE", 1);
				pp.put("LIVE_START", DateUtil.getTime());
			} else if (pd.getString("action").equals("publish_done")) {
				pp.put("LIVE_ONLINE", 0);
				pp.put("LIVE_END", DateUtil.getTime());
			}
			liveInService.updUserOnline(pp);
			response.setStatus(200);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
	}

	/**
	 * @Function 直播模块中的模糊查询用户接口
	 * @Author 于泓磊
	 * @Date 2018年1月31日
	 */
	@RequestMapping(value = "/getuserlist")
	@ResponseBody
	public Object getUserList() {
		logBefore(logger, "直播模块中的模糊查询用户接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("USERLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("likeuserlist", pd)) { // 检查参数
					pd.put("NICKNAME", "%" + pd.getString("NICKNAME") + "%");
					List<PageData> list = userinService.getLikeNickNameList(pd);
					if (list.size() != 0) {
						map.put("pd", list);
					}
					result = (0 == list.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 给主播送礼物接口
	 * @Author 于泓磊
	 * @Date 2018年1月31日
	 */
	@RequestMapping(value = "/gifttouser")
	@ResponseBody
	public synchronized Object updBlackCoinUser() {
		logBefore(logger, "给主播送礼物接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("GIFT", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("gifttouser", pd)) { // 检查参数
					// pd需要有的参数:扣除的黑咖币数量,赠送人的id和主播的id,先检验赠送人账户中有无足够的黑咖币数量
					// 查询当前用户账户中黑咖币是否大于扣除的数量,大于的话直接扣除并处理后,将黑咖币送给主播
					if (liveInService.getBlackCoin(pd).getLong("USERCOUNT") > 0) {
						// 将送礼物的黑咖币数量从账户中扣除
						pd.put("TYPE", 0);
						liveInService.updBlackCoin(pd);
						// 将礼物数额进行扣费之后存入主播的账户中
						pd.put("TYPE", 1);
						String BLACKPRICE = pd.getString("BLACKPRICE");
						String REHONOURUSER_ID = pd.getString("REHONOURUSER_ID");
						String HONOURUSER_ID = pd.getString("HONOURUSER_ID");

						pd.put("BLACKPRICE", (Integer.parseInt(BLACKPRICE) * 0.8));
						pd.put("HONOURUSER_ID", REHONOURUSER_ID);
						liveInService.updBlackCoin(pd);
						pd.put("REHONOURUSER_ID", REHONOURUSER_ID);
						pd.put("HONOURUSER_ID", HONOURUSER_ID);
						// 获取当前用户是否已经完成礼物上传，如果完成，则任务更新
						PageData page = liveInService.getTaskStatus(pd);
						// 判断数据库中任务是否完成,如果未完成则变成完成状态并添加相应的黑咖币
						if (page.getInterger("TASK_GIFT") == 0) {
							pd.put("TASK_GIFT", 1);
							pd.put("BLACKCOIN", 50);
							liveInService.updTaskStatus(pd);
						}
						// 检查排行榜是否有该用户给主播的送礼记录
						PageData existRanking = liveInService.isExistRanking(pd);
						// 日榜名称
						String redisDate = "DATE" + REHONOURUSER_ID;
						// 周榜名称
						String redisWeek = "WEEK" + REHONOURUSER_ID;
						// 月榜名称
						String redisMonth = "MONTH" + REHONOURUSER_ID;
						// 总榜信息存在数据库
						if (existRanking.getLong("USERCOUNT") > 0) {
							// 有记录则更新排行榜信息
							pd.put("PKPARA", existRanking.getInterger("PKPARA") + Integer.parseInt(BLACKPRICE));
							liveInService.updRankingList(pd);
						} else {
							// 无记录则添加排行榜信息
							pd.put("RANKING_ID", this.getSnowId());
							pd.put("PKPARA", BLACKPRICE);
							liveInService.addRankingList(pd);
						}
						// 将数据添加到Redis缓存中
						// 添加日榜信息
						redisDaoImpl.zadd(redisDate, HONOURUSER_ID, Double.parseDouble(BLACKPRICE));
						redisDaoImpl.expireTomorrow(redisDate);
						// 添加周榜信息
						redisDaoImpl.zadd(redisWeek, HONOURUSER_ID, Double.parseDouble(BLACKPRICE));
						redisDaoImpl.expireWeek(redisWeek);
						// 添加月榜信息
						redisDaoImpl.zadd(redisMonth, HONOURUSER_ID, Double.parseDouble(BLACKPRICE));
						redisDaoImpl.expireMonth(redisMonth);
						result = "01";
					} else {
						// 账户余额不足
						result = "07";
					}
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 获取直播中个人信息黑微博接口
	 * @Author 于泓磊
	 * @Date 2018年2月1日
	 */
	@RequestMapping(value = "/getweibouser")
	@ResponseBody
	public synchronized Object getWeiboUser() {
		logBefore(logger, "获取直播中个人信息黑微博接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		ArrayList<String> ids = new ArrayList<>();
		String result = "00";
		try {
			if (Tools.checkKey("WEIBOUSER", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) { // 检查参数(检验HONOURUSER_ID)
					// 将我的id保存到集合中
					ids.add(pd.getString("HONOURUSER_ID"));
					pd.put("ids", ids);
					// 遍历获取我所有圈子并根据时间排序
					List<PageData> list = circleInService.getAllCircleListByIds(pd);
					// 获取点赞数和评论数
					PageData dotp = new PageData();
					for (PageData pageData : list) {
						ToolsUtil.putImgstoArray(pageData, "SHOWIMAGES");
						dotp.put("CIRCLE_ID", pageData.get("CIRCLE_ID")); // 查看的圈子id
						dotp.put("HONOURUSER_ID", pd.get("HONOURUSER_ID")); // 我的id
						PageData p = circleInService.getDotAgreeMy(dotp);
						if (p != null) {
							pageData.put("STATUS", "1"); // 1为点赞
						} else {
							pageData.put("STATUS", "0"); // 0为没有点过赞
						}
					}
					if (list.size() != 0) {
						map.put("pd", list);
					}
					result = (0 == list.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 直播个人资料上部分个人资料接口
	 * @Author 于泓磊
	 * @Date 2018年2月1日
	 */
	@RequestMapping(value = "/getuserdata")
	@ResponseBody
	public synchronized Object getUpUserData() {
		logBefore(logger, "直播个人资料上部分个人资料接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("USERDATA", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) { // 检查参数(检验HONOURUSER_ID)
					pd = liveInService.getUserData(pd);
					if (pd.getInterger("LIVE_ONLINE") == 1) {
						PageData pullAddress = LiveUtil.getPullAddress("ZSHApp", pd.getString("STREAMNAME"));
						pd.put("PublishUrl", pullAddress.getString("PublishUrl"));

					} else if (pd.getInterger("LIVE_ONLINE") == 0) {
						pd.put("PublishUrl", "");
					}
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 直播个人资料下部分资料接口
	 * @Author 于泓磊
	 * @Date 2018年2月2日
	 */
	@RequestMapping(value = "/getdowndata")
	@ResponseBody
	public synchronized Object getDownData() {
		logBefore(logger, "直播个人资料下部分资料接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("DOWNDATA", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) { // 检查参数(检验HONOURUSER_ID)
					pd = liveInService.getDownUserData(pd);
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 直播页面点击头像显示的简洁个人资料接口
	 * @Author 于泓磊
	 * @Date 2018年2月2日
	 */
	@RequestMapping(value = "/getpithydata")
	@ResponseBody
	public synchronized Object getPithyData() {
		logBefore(logger, "直播页面点击头像显示的简洁个人资料接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("PITHYDATA", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("manyUserId", pd)) {
					pd = liveInService.getPithyData(pd);
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 直播页中'我的'页面接口
	 * @Author 于泓磊
	 * @Date 2018年2月2日
	 */
	@RequestMapping(value = "/getminedata")
	@ResponseBody
	public synchronized Object getMineData() {
		logBefore(logger, "直播页中'我的'页面接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("MINEDATA", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) {
					pd = liveInService.getMineData(pd);
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 获得粉丝列表接口
	 * @Author 于泓磊
	 * @Date 2018年2月2日
	 */
	@RequestMapping(value = "/getfanslist")
	@ResponseBody
	public synchronized Object getFansList() {
		logBefore(logger, "获得粉丝列表接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("FANSLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) {
					List<PageData> list = liveInService.getFansList(pd);
					if (list.size() != 0) {
						map.put("pd", list);
					}
					result = (0 == list.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 获得关注列表接口
	 * @Author 于泓磊
	 * @Date 2018年2月2日
	 */
	@RequestMapping(value = "/getfocuslist")
	@ResponseBody
	public synchronized Object getFocusList() {
		logBefore(logger, "获得关注列表接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("FOCUSLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) {
					List<PageData> list = liveInService.getFocusList(pd);
					if (list.size() != 0) {
						map.put("pd", list);
					}
					result = (0 == list.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 用户签到接口
	 * @Author 于泓磊
	 * @Date 2018年2月5日
	 */
	@RequestMapping(value = "/usercheckin")
	@ResponseBody
	public synchronized Object userCheckIn() {
		logBefore(logger, "用户签到接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("CHECKIN", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) {
					PageData checkIn = liveInService.getCheckIn(pd);
					if (checkIn.getLong("USERCOUNT") != 0) {
						if (checkIn.get("CHECK_DATE").equals(DateUtil.getDay())) {
							System.out.println("该id已经签到过了");
							result = "08";
						} else {
							System.out.println("该id还未签到");
							pd.put("TODAY", DateUtil.getDay());
							pd.put("YESTERDAY", DateUtil.getBeforeDays(1));
							if (DateUtil.getMonth().equals(checkIn.getString("CHECK_DATE").substring(5, 7))) {
								pd.put("CHECK_DATES", checkIn.getString("CHECK_DATES") + "," + DateUtil.getDate());
							} else {
								pd.put("CHECK_DATES", DateUtil.getDate());
							}
							liveInService.updCheckIn(pd);
							result = "01";
						}
					} else {
						System.out.println("该id从没签到过");
						pd.put("CHECK_ID", this.getSnowId());
						pd.put("CHECK_DATE", DateUtil.getDay());
						pd.put("CHECK_INDAYS", 1);
						pd.put("CHECK_DATES", DateUtil.getDate());
						liveInService.addCheckIn(pd);
						result = "01";
					}
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 获取签到日期及连续签到天数接口
	 * @Author 于泓磊
	 * @Date 2018年2月5日
	 */
	@RequestMapping(value = "/getcheckin")
	@ResponseBody
	public synchronized Object getCheckIn() {
		logBefore(logger, "获取签到日期及连续签到天数接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("CHECKIN", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getFriendList", pd)) {
					pd = liveInService.getCheckInlog(pd);
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Function 获取排行榜信息接口
	 * @Author 于泓磊
	 * @Date 2018年2月5日
	 */
	@RequestMapping(value = "/getrankinglist")
	@ResponseBody
	public synchronized Object getRankingList() {
		logBefore(logger, "获取排行榜信息接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		List<PageData> list = new ArrayList<>();
		try {
			if (Tools.checkKey("RANKING", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getRankingList", pd)) {
					if (pd.getString("TYPE").equals("ALL")) {
						list = liveInService.getRankingList(pd);
					}else{
					// 调用Redis,从Redis中获取当前排行榜数据
					Set<Tuple> zrevrange = redisDaoImpl.zrevrange(pd.getString("TYPE") + pd.getString("HONOURUSER_ID"),
							0, 9);
					for (Tuple tuple : zrevrange) {
						pd.put("HONOURUSER_ID", tuple.getElement());
						PageData userPortrait = userinService.getPortNickName(pd);
							userPortrait.put("PKPARA", tuple.getScore());
						list.add(userPortrait);
					}
					}
					if (list.size() != 0) {
						map.put("pd", list);
					}
					result = (0 == list.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 
	 * @Title: getRankingList 
	 * @Description: 任务中心任务完成情况
	 * @Author:Mr.Yu 
	 * @return: Object 
	 * @Date: 2018年2月23日
	 * @throws
	 */
	@RequestMapping(value = "/gettaskstatus")
	@ResponseBody
	public synchronized Object getTaskStatus() {
		logBefore(logger, "任务中心任务完成情况接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("TASK", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("honEvaList", pd)) {
					pd = liveInService.getTaskStatus(pd);
					// 从数据库读取数据,如果其他任务都完成则将全部任务属性修改为已完成，并添加响应黑咖币
					if (pd.getInterger("TASK_PORT") == 1 && pd.getInterger("TASK_BROWSE") == 1
							&& pd.getInterger("TASK_ATTENTION") == 1 && pd.getInterger("TASK_GIFT") == 1
							&& pd.getInterger("TASK_ALL") == 0) {
						pd.put("TASK_ALL", 1);
						pd.put("BLACKCOIN", 100);
						liveInService.updTaskStatus(pd);
					}
					pd = liveInService.getTaskStatus(pd);
					map.put("pd", pd);
					result = (null == pd) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * @Title: getRankingList 
	 * @Description: 用户观看直播次数任务统计接口
	 * @return 
	 * @Author: Mr.Yu 
	 * @return: Object 
	 * @Date: 2018年2月24日 
	 * @throws
	 */
	@RequestMapping(value = "/numberoftimes")
	@ResponseBody
	public synchronized Object getNumberOfTimes() {
		logBefore(logger, "用户观看直播次数任务统计接口 ");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("NUMBER", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("honEvaList", pd)) {
					PageData taskStatus = liveInService.getTaskStatus(pd);
					if (taskStatus.getInterger("TASK_BROWSE") == 0) {
						// 在Redis中做累加
						redisDaoImpl.incrby("Task" + pd.getString("HONOURUSER_ID"), 1);
						// 获取到Redis中对应key的值,就是用户观看直播次数的值
						Integer count = Integer.parseInt(redisDaoImpl.get("Task" + pd.getString("HONOURUSER_ID")));
						// 如果该值大于3，则从Redis中清除，并修改数据库
						if (count >= 3) {
							redisDaoImpl.delete("Task" + pd.getString("HONOURUSER_ID"));
							pd.put("TASK_BROWSE", 1);
							pd.put("BLACKCOIN", 20);
							liveInService.updTaskStatus(pd);
						}
					}
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	
	
	
	

	/**
	 * 获取一个推流地址
	 * 
	 * @param AppName
	 *            App名称用作推流地址
	 * @param StreamType
	 *            推流所属类型(game游戏,music唱歌等等自定义类型就可以)
	 * @return
	 */
	public synchronized PageData getPushAddress(String HONOURUSER_ID, String AppName, String StreamType) {
		String StreamName = StreamType + SnowIdUtil.getStreamNameByUUId();
		PageData pd = new PageData();
		String pushAddress = "rtmp://video-center.alivecdn.com/" + AppName + "/" + StreamName
				+ "?vhost=live.rongyaohk.com&auth_key=" + LiveUtil.getAuth_Key(3600, AppName, StreamName, "zsh2018");
		pd.put("PUSHADDRESS", pushAddress);
		PageData p = new PageData();
		p.put("STREAMNAME", StreamName);
		p.put("HONOURUSER_ID", HONOURUSER_ID);
		System.out.println("p:" + p);
		try {
			liveInService.updStreamName(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pd;

	}

	/**
	 * 获取所有在线的推流地址
	 * 
	 * @param DomainName
	 *            直播域名
	 * @param AppName
	 *            App名称
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public PageData getPushOnline(PageData pds, String DomainName, String AppName) {
		HttpResponse httpResponse = new HttpResponse();
		//初始化Client
		IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIWSHYz0eMok7e",
				"3cP4cK9GrmiFyBYezhRx7SpYW11kWD");
		IAcsClient client = new DefaultAcsClient(profile);
		//初始化请求
		DescribeLiveStreamsOnlineListRequest describeLiveStreamsOnlineListRequest = new DescribeLiveStreamsOnlineListRequest();
		describeLiveStreamsOnlineListRequest.setDomainName(DomainName);
		describeLiveStreamsOnlineListRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
		PageData pd = new PageData();
		try {
			//发起openAPI调用并解析结果
			httpResponse = client.doAction(describeLiveStreamsOnlineListRequest);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		String OnlineInfo = new String(httpResponse.getHttpContent());
		PageData fromJson = gson.fromJson(OnlineInfo, PageData.class);
		String json = gson.toJson(fromJson.get("OnlineInfo"));//正在推送流的信息。
		PageData fromJson2 = gson.fromJson(json, PageData.class);
		List<PageData> list = new ArrayList<>();
		List<PageData> notlist = new ArrayList<>();
		if (fromJson2.get("LiveStreamOnlineInfo") != null) {
			list = (List<PageData>) fromJson2.get("LiveStreamOnlineInfo");
			String json2 = gson.toJson(list);
			try {
				list = ToolsUtil.fromJson(json2, PageData.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (PageData pageData : list) {
				if (pds.getString("LIVETYPE_ID") == null) {
					logger.info("流所属应用名称AppName="+pageData.get("AppName"));
					logger.info("流所属加速域名DomainName="+pageData.get("DomainName"));
					logger.info("直播推流域名PublishDomain="+pageData.get("PublishDomain"));
					pageData.remove("AppName");       //流所属应用名称。
					pageData.remove("DomainName");    //流所属加速域名。
					pageData.remove("PublishDomain");//直播推流域名，使用中心推流的可直接填写播放域名
					// 将在线人数赋予对象
					pageData.put("UserNumber",
							LiveUtil.getUserOnline(DomainName, AppName, pageData.getString("StreamName")));
					try {
						// 获取该对象在数据库中的标题和封面
						PageData liveCoverTitle = liveInService.getLiveCoverTitle(pageData);
						pageData.put("LiveCover", liveCoverTitle.get("LIVE_COVER"));
						pageData.put("LiveTitle", liveCoverTitle.get("LIVE_TITLE"));
					} catch (Exception e) {
						e.printStackTrace();
					}
					// 将授权过后的推流地址赋予对象     
					//PublishUrl   推流完整 URL地址；例：rtmp://play.aliyunlive.com/AppName/StreamName
					pageData.put("PublishUrl", pageData.get("PublishUrl") + "?auth_key="
							+ LiveUtil.getAuth_Key(3600, AppName, pageData.getString("StreamName"), "zsh2018"));
					pageData.remove("StreamName");
					notlist.add(pageData);
				} // 如果参数中有LIVE_TYPE则根据直播分类来获取推流地址(直播分类列表)
				else {
					try {
						// 获得所有分类的ID
						PageData liveCoverTitle = liveInService.getLiveCoverTitle(pageData);
						System.out.println("liveCoverTitle:" + liveCoverTitle);
						// 如果分类id和传过来的分类id相同,则获取所有该分类下的拉流地址
						if (liveCoverTitle.getString("LIVE_TYPE").equals(pds.getString("LIVETYPE_ID"))) {
							// 数据截取
							pageData.remove("AppName");
							pageData.remove("DomainName");
							pageData.remove("PublishDomain");
							// 获取该拉流在线人数
							pageData.put("UserNumber",
									LiveUtil.getUserOnline(DomainName, AppName, pageData.getString("StreamName")));
							// 直播封面
							pageData.put("LiveCover", liveCoverTitle.get("LIVE_COVER"));
							// 直播标题
							pageData.put("LiveTitle", liveCoverTitle.get("LIVE_TITLE"));
							notlist.add(pageData);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					pageData.put("PublishUrl", pageData.get("PublishUrl") + "?auth_key="
							+ LiveUtil.getAuth_Key(3600, AppName, pageData.getString("StreamName"), "zsh2018"));
					pageData.remove("StreamName");

				}
			}
		}
		fromJson2.put("LiveStreamOnlineInfo", notlist);
		fromJson.put("OnlineInfo", fromJson2);
		pd.put("PUSHONLINE", gson.toJson(fromJson));
		return pd;
	}

	/**
	 * 获取附近正在直播的主播列表
	 * 
	 * @param DomainName
	 *            直播域名
	 * @param AppName
	 *            App名称
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public PageData getNearByPushOnline(String HONOURUSER_ID, String DomainName, String AppName) {
		HttpResponse httpResponse = new HttpResponse();
		IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIWSHYz0eMok7e",
				"3cP4cK9GrmiFyBYezhRx7SpYW11kWD");
		IAcsClient client = new DefaultAcsClient(profile);
		DescribeLiveStreamsOnlineListRequest describeLiveStreamsOnlineListRequest = new DescribeLiveStreamsOnlineListRequest();
		describeLiveStreamsOnlineListRequest.setDomainName(DomainName);
		describeLiveStreamsOnlineListRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
		PageData pd = new PageData();
		try {
			httpResponse = client.doAction(describeLiveStreamsOnlineListRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String OnlineInfo = new String(httpResponse.getHttpContent());
		PageData fromJson = gson.fromJson(OnlineInfo, PageData.class);
		String json = gson.toJson(fromJson.get("OnlineInfo"));
		PageData fromJson2 = gson.fromJson(json, PageData.class);
		List<PageData> list = new ArrayList<>();
		List<PageData> notlist = new ArrayList<>();
		if (fromJson2.get("LiveStreamOnlineInfo") != null) {
			list = (List<PageData>) fromJson2.get("LiveStreamOnlineInfo");
			String json2 = gson.toJson(list);
			try {
				list = ToolsUtil.fromJson(json2, PageData.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (PageData pageData : list) {
				try {
					// 获取指定距离以内的坐标
					pd.put("HONOURUSER_ID", HONOURUSER_ID);
					// 获取规定范围内正在直播的主播的最大范围经纬度
					double[] rectangle = ToolsUtil.getRectangle(userinService.getTrapeze(pd).getString("USERLONGITUDE"),
							userinService.getTrapeze(pd).getString("USERLATITUDE"), 1000);
					for (PageData d : liveInService.getNearByPerson(pd)) {
						// 如果在当前登录用户规定范围内，则添加到集合中
						if (Double.parseDouble(d.getString("USERLONGITUDE")) > rectangle[0]
								&& Double.parseDouble(d.getString("USERLATITUDE")) > rectangle[1]
								&& Double.parseDouble(d.getString("USERLONGITUDE")) < rectangle[2]
								&& Double.parseDouble(d.getString("USERLATITUDE")) < rectangle[3]) {
							pageData.remove("AppName");
							pageData.remove("DomainName");
							pageData.remove("PublishDomain");
							pageData.put("UserNumber",
									LiveUtil.getUserOnline(DomainName, AppName, pageData.getString("StreamName")));
							PageData liveCoverTitle = liveInService.getLiveCoverTitle(pageData);
							System.out.println("LIVECOVER:" + liveCoverTitle);
							pageData.put("LiveCover", liveCoverTitle.getString("LIVE_COVER"));
							pageData.put("LiveTitle", liveCoverTitle.getString("LIVE_TITLE"));
							pageData.put("PublishUrl", pageData.get("PublishUrl") + "?auth_key="
									+ LiveUtil.getAuth_Key(3600, AppName, pageData.getString("StreamName"), "zsh2018"));
							pageData.remove("StreamName");
							notlist.add(pageData);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				pd.remove("HONOURUSER_ID");
			}
		}
		fromJson2.put("LiveStreamOnlineInfo", notlist);
		fromJson.put("OnlineInfo", fromJson2);
		pd.put("PUSHONLINE", gson.toJson(fromJson));
		return pd;
	}

	/**
	 * 获取筛选之后的所有在线推流地址
	 * 
	 * @param DomainName
	 *            直播域名
	 * @param AppName
	 *            App名称
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public PageData getScreenOnline(PageData pds, String DomainName, String AppName) {
		HttpResponse httpResponse = new HttpResponse();
		IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIWSHYz0eMok7e",
				"3cP4cK9GrmiFyBYezhRx7SpYW11kWD");
		IAcsClient client = new DefaultAcsClient(profile);
		DescribeLiveStreamsOnlineListRequest describeLiveStreamsOnlineListRequest = new DescribeLiveStreamsOnlineListRequest();
		describeLiveStreamsOnlineListRequest.setDomainName(DomainName);
		describeLiveStreamsOnlineListRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
		PageData pd = new PageData();
		try {
			httpResponse = client.doAction(describeLiveStreamsOnlineListRequest);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		String OnlineInfo = new String(httpResponse.getHttpContent());
		PageData fromJson = gson.fromJson(OnlineInfo, PageData.class);
		String json = gson.toJson(fromJson.get("OnlineInfo"));
		PageData fromJson2 = gson.fromJson(json, PageData.class);
		List<PageData> list = new ArrayList<>();
		List<PageData> notlist = new ArrayList<>();
		if (fromJson2.get("LiveStreamOnlineInfo") != null) {
			list = (List<PageData>) fromJson2.get("LiveStreamOnlineInfo");
			String json2 = gson.toJson(list);
			try {
				list = ToolsUtil.fromJson(json2, PageData.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (PageData pageData : list) {
				try {
					for (PageData page : liveInService.getScreenList(pds)) {
						pageData.remove("AppName");
						pageData.remove("DomainName");
						pageData.remove("PublishDomain");
						pageData.put("UserNumber",
								LiveUtil.getUserOnline(DomainName, AppName, pageData.getString("StreamName")));
						try {
							pageData.put("LiveCover", page.getString("LIVE_COVER"));
							pageData.put("LiveTitle", page.getString("LIVE_TITLE"));
						} catch (Exception e) {
							e.printStackTrace();
						}
						pageData.put("PublishUrl", pageData.get("PublishUrl") + "?auth_key="
								+ LiveUtil.getAuth_Key(3600, AppName, pageData.getString("StreamName"), "zsh2018"));
						pageData.remove("StreamName");
						notlist.add(pageData);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}

			}
		}
		fromJson2.put("LiveStreamOnlineInfo", notlist);
		fromJson.put("OnlineInfo", fromJson2);
		pd.put("PUSHONLINE", gson.toJson(fromJson));
		return pd;
	}

}
